package view;

import static java.awt.BorderLayout.CENTER;
import static java.awt.BorderLayout.NORTH;
import static java.awt.BorderLayout.SOUTH;
import static java.awt.BorderLayout.WEST;
import java.awt.BorderLayout;
import java.util.Iterator;
import java.util.Map;

import javax.swing.JFrame;

import xl.Address;

import model.Cell;
import model.CurrentSlot;
import model.Sheet;
import control.ExitListener;
import control.XLMenuBar;

public class Gui extends JFrame {
    private static final int ROWS = 10, COLUMNS = 8;
    private GuiList guiList;
    private StatusArea statusArea;
    private int count;
    private Sheet sheet;

    private Gui(GuiList guiList, int count) {
        super("Untitled-" + count);
        this.guiList = guiList;
        this.count = count;
        this.sheet = new Sheet();
        this.statusArea = new StatusArea();
        
        CurrentSlot currentSlot = new CurrentSlot();
        Editor editor = new Editor(sheet, currentSlot, statusArea);
        BorderPanel statusPanel = new BorderPanel();
        CurrentView currentView = new CurrentView();
        currentSlot.addObserver(currentView);
        currentSlot.addObserver(editor);
        SheetView sheetView = new SheetView(ROWS, COLUMNS, currentSlot);
        
        setLocation(count * 20, count * 20);
        guiList.add(this);
        setLayout(new BorderLayout());
        // statusPanel
        statusPanel.add(WEST, currentView);
        statusPanel.add(CENTER, statusArea);
        // sheetPanel
        BorderPanel sheetPanel = new BorderPanel();
        sheetView.setSheet(sheet);
        sheetPanel.add(WEST, new RowNumberPanel(ROWS));
        sheetPanel.add(CENTER, sheetView);
        // gui
        add(NORTH, statusPanel);
        add(CENTER, editor);
        add(SOUTH, sheetPanel);
        setJMenuBar(new XLMenuBar(this, guiList, statusArea));
        addWindowListener(new ExitListener(this, guiList));
        pack();
        setResizable(false);
        setVisible(true);
        // sheet-observers
        
        sheet.addObserver(currentView);
        sheet.addObserver(editor);
        sheet.addObserver(sheetView);
    }

    public Gui(Gui oldGui) {
        this(oldGui.guiList, oldGui.count + 1);
        Iterator<Gui> i = guiList.iterator();
        while (i.hasNext()) {
        	Gui g = i.next();
        	if (g != guiList.last()) {
        		g.count++;
        	}
        }
    }

    public void rename(String title) {
        setTitle(title);
        guiList.setChanged();
    }
    
    public Sheet getSheet() {
    	return sheet;
    }
    
    public static void main(String[] args) {
        new Gui(new GuiList(), 0);
    }
    
    public void replaceSheet(Map<Address, Cell> replacementSheet) {
    	sheet.replaceSheet(replacementSheet);
    }

}